package org.lanyu.springainovel.common.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.lanyu.springainovel.common.vo.FluxVO;
import org.lanyu.springainovel.chat.vo.QuestionVO;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.util.ArrayList;
import java.util.List;

@Tag(name = "智能体工作流", description = "智能体工作流")
@RestController
@RequestMapping("/workflow")
@CrossOrigin(origins = "*")
public class AgentController {

    public AgentController() {
        super();
    }

    @PostMapping(value = "/generateStream", produces = "text/event-stream;charset=UTF-8")
    public Flux<FluxVO> generateStream(@RequestBody QuestionVO questionVO) {
        // 1. 初始状态通知
        Flux<FluxVO> initFlux = Flux.just(
                FluxVO.builder().text("工作流启动中，正在处理您的请�?..").status("running").build(),
                FluxVO.builder().text("开始分析任务需�?..").status("running").build()
        );

        // 2. 创建工作流执行逻辑
        Mono<List<String>> workflowExecution = Mono.fromCallable(() -> {
            // 模拟工作流节点执�?
            List<String> results = new ArrayList<>();

            // 节点1: 需求分�?
            results.add("需求分析节点完�? " + analyzeRequirement(questionVO.getMessage()));
            Thread.sleep(500); // 模拟处理时间

            // 节点2: 任务拆解
            results.add("任务拆解节点完成: " + breakDownTasks(questionVO.getMessage()));
            Thread.sleep(3000);

            // 节点3: 子任务处�?
            results.add("子任务处理节点完�? " + processSubTasks(questionVO.getMessage()));
            Thread.sleep(1200);

            // 节点4: 结果汇�?
            results.add("结果汇总节点完�? " + summarizeResults(results));

            return results;
        }).subscribeOn(Schedulers.boundedElastic());

        // 3. 将工作流执行结果转换为流式响�?
        Flux<FluxVO> resultFlux = workflowExecution.flatMapMany(results ->
                Flux.fromIterable(results)
                        .map(result -> FluxVO.builder().text(result).status("running").build())
                        .concatWithValues(FluxVO.builder().text("工作流执行完成").status("running").build())
        );

        // 4. 合并初始通知和结果流
        return initFlux.concatWith(resultFlux);
    }

    private String analyzeRequirement(String message) {
        return "已识别" + message.split(" ").length + "个关键需求点";
    }

    private String breakDownTasks(String message) {
        return "生成" + (message.length() / 10 + 1) + "个子任务";
    }

    private String processSubTasks(String message) {
        return "处理完成" + message.length() + "个字符的内容";
    }

    private String summarizeResults(List<String> results) {
        return "汇总" + results.size() + "个节点的处理结果";
    }

}
